package com.ziguang.redwood.admin.controller;

import java.io.File;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.ziguang.common.SysConstant;
import com.ziguang.common.interceptor.AuthInterceptor;
import com.ziguang.redwood.admin.service.NewsService;
import com.ziguang.redwood.admin.validator.NewsValidator;

@ControllerBind(controllerKey = "/news", viewPath = "/admin")
@Before(AuthInterceptor.class)
public class NewsController extends Controller {
	private static final Logger log  = LoggerFactory.getLogger(NewsController.class);
	
	/**
	 * 获取新闻动态数据
	 */
	public void index() {
		List<Record> data = NewsService.me.index();
		setAttr("data", data);
		render("news.html");
	}
	
	/**
	 * 获取当前数据
	 */
	public void edit(){
		String id = this.getPara("id");
		if(id != ""){
			Record data = NewsService.me.QueryEdit(id);
			setAttr("data",data);
			render("news_edit.html");
		}else{
			render("news_edit.html");
		}
	}
	
	/**
	 * 保存编辑数据
	 */
	@Before(NewsValidator.class)
	public void save(){
		String id = this.getPara("id");
		String title = this.getPara("title");
		String content = this.getPara("content");
		NewsService.me.save(id,title,content);
		renderJson("{\"code\":0}");
	}
	
	/**
	 * 删除当前数据
	 */
	public void delete(){
		String id = this.getPara("id");
		NewsService.me.delete(id);
		renderJson("{\"code\":0}");
	}
	
	
	public void saveImg(){
		// 文件上传
		UploadFile img = getFile("myFileName");
		String RootPath = SysConstant.UPLOAD_ROOT_PATH;
		String imgRootPath = getSessionAttr(SysConstant.SESSION_INFO);
		String imgPath = imgRootPath + File.separator + System.currentTimeMillis();
		File file = new File(RootPath+"news"+File.separator+imgPath);
		if(!file.exists()){
			file.mkdirs();
		}
		String imgName = img.getFileName();
		String homeImg = RootPath+"news"+File.separator+imgPath+File.separator+imgName;
		img.getFile().renameTo(new File(homeImg));
		String sqlImgUrl = imgPath+File.separator+imgName;
		renderText(sqlImgUrl);
	}
	
	
}
